<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
  
    <script>
   const arr=   [
  {
    id: "604e21feb205b95968e13129",
    name: "总裁办",
    pid: "0",
    children: []
  }, 
  {
    id: "604e222bb205b95968e1312a",
    name: "行政部",
    pid: "0",
    children: []
  },
  {
    pid: "0",
    id: "604e2251b205b95968e1312c",
    name: "财务部",
    children: [
      {
        pid: "604e2251b205b95968e1312c",
        id: "604e2262b205b95968e1312d",
        name: "财务核算部",
      },
      {
        pid: "604e2251b205b95968e1312c",
        id: "604e227db205b95968e1312e",
        name: "税务管理部",
      },
      {
        pid: "604e2251b205b95968e1312c",
        id: "604e2297b205b95968e1312f",
        name: "薪资管理部",
      }
    ]
  },
  {
    pid: "0",
    id: "6051ad90e93db6522c1d00d2",
    name: "技术部",
    children: [
      {
        pid: "6051ad90e93db6522c1d00d2",
        id: "6051adb6e93db6522c1d00d3",
        name: "Java研发部",
      },
      {
        pid: "6051ad90e93db6522c1d00d2",
        id: "6051add6e93db6522c1d00d4",
        name: "Python研发部",
      },
      {
        pid: "6051ad90e93db6522c1d00d2",
        id: "6051adefe93db6522c1d00d5",
        name: "Php研发部",
      }
    ]
  }
]
        function ToTree(items) {
  const result = []; 
  const itemMap = {};  // 
  for (let i = 0; i < items.length; i++) {
    const id = items[i].id;
    const pid = items[i].pid;
    // 先转成map存储
    if (!itemMap[id]) {
      itemMap[id] = {
        children: [],
      }
    }

    itemMap[id] = {
      ...items[i],
      children: itemMap[id]['children']
    }

    const treeItem =  itemMap[id];

    if (pid === '0') {
      result.push(treeItem);
    } else {
      if (!itemMap[pid]) {
        itemMap[pid] = {
          children: [],
        }
      }
      itemMap[pid].children.push(treeItem)
    }

  }
  return result;
}
ToTree(arr)
    </script>
</body>
</html>